package org.jks.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jks.config.Config;
import org.jks.constant.Constants;
import org.jks.constant.SysConfig;
import org.jks.model.Department;
import org.jks.model.Device;
import org.jks.model.DeviceRecipient;
import org.jks.model.Flight;
import org.jks.model.RecipientOrder;
import org.jks.model.User;
import org.jks.model.Work;
import org.jks.model.WorkType;
import org.jks.request.model.Ids;
import org.jks.request.model.UIDeviceRecipient;
import org.jks.request.model.UIRecipientOrder;
import org.jks.request.model.UISearchWork;
import org.jks.request.model.UIWork;
import org.jks.response.model.ActionResult;
import org.jks.response.model.UIFile;
import org.jks.response.model.UITable;
import org.jks.service.DeviceInOutService;
import org.jks.service.DeviceRecipientService;
import org.jks.service.DeviceService;
import org.jks.service.DeviceStatusService;
import org.jks.service.WorkDeviceService;
import org.jks.service.WorkService;
import org.jks.service.WorkTypeService;
import org.jks.util.DateUtil;
import org.jks.util.FileUtil;
import org.jks.util.JsonUtil;
import org.jks.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/work")
public class WorkController {
	public static final int TYPE_AUTO = 1;
	public static final int TYPE_DEFECT = 2;
	public static final int TYPE_VEDIO = 3;
	
	@Autowired
	WorkService workService;
	@Autowired
	WorkDeviceService workDeviceService;
	@Autowired
	WorkTypeService workTypeService;
	@Autowired
	DeviceRecipientService deviceRecipientService;
	@Autowired
	DeviceInOutService deviceInOutService;
	@Autowired
	DeviceStatusService deviceStatusService;
	@Autowired
	DeviceService deviceService;

	
	@RequestMapping("/add")
	public void add(HttpServletRequest request, HttpServletResponse response, 
			HttpSession session){
		ActionResult ar = new ActionResult();
		
		String json = "";
		String OrderNo = "DR_" + DateUtil.toString(new Date(), "yyyyMMddHHmmss");
		DeviceRecipient deviceRecipient = new DeviceRecipient();
		
		try {
			json = JsonUtil.getJson(request.getReader());
			UIWork uiWork = (UIWork)JsonUtil.Json2Object(json, UIWork.class);
			UIDeviceRecipient uiDeviceRecipient = uiWork.getDeviceRecipient();
			Date workTime = DateUtil.toDate(uiDeviceRecipient.getTime(), "yyyy-MM-dd HH:mm:ss");
			
			Department department = new Department();
			department.setId(uiDeviceRecipient.getDepartmentId());
			deviceRecipient.setDepartment(department);
			Flight group = new Flight();
			group.setId(uiDeviceRecipient.getGroupId()); 
			deviceRecipient.setGroup(group);
			deviceRecipient.setTime(workTime);
			User user = new User();
			user.setId(uiDeviceRecipient.getUserId());
			deviceRecipient.setRecipients(user);
			deviceRecipient.setDesp(uiDeviceRecipient.getDesp());
			deviceRecipient.setOrderNo(OrderNo);
			
			List<RecipientOrder> recipientOrders = new ArrayList<RecipientOrder>();
			for(UIRecipientOrder uiRecipientOrder : uiDeviceRecipient.getOrders()){
				RecipientOrder recipientOrder = new RecipientOrder();
				Device device = new Device();
				device.setId(uiRecipientOrder.getDeviceId());
				recipientOrder.setDevice(device);
				recipientOrder.setCount(uiRecipientOrder.getCount());
				recipientOrder.setDeviceRecipient(deviceRecipient);
				recipientOrders.add(recipientOrder);
			}
			deviceRecipient.setRecipientOrders(recipientOrders);
			deviceRecipientService.save(deviceRecipient);
			
			WorkType workType = workTypeService.findById(uiWork.getWorkType());
			Work work = new Work();
			work.setName(uiWork.getName());
			work.setWorktime(workTime);
			work.setEndTime(null);
			work.setWorktype(workType);
			work.setDeviceRecipient(deviceRecipient);
			work.setWorker(user);
			workService.save(work);
			if(uiWork.getWorkType() == 1){
				
			}
			else if(uiWork.getWorkType() == 2){
				String basePath = request.getServletContext().getRealPath("/");
				String workBase = basePath + File.separator + SysConfig.ATTACHEMENT + File.separator + SysConfig.WORK_DIR + File.separator + "飞巡作业" + File.separator + uiWork.getName();
				File file = new File(workBase);
				if(!file.exists()){
					file.mkdirs();
				}
				String workDefectImg = workBase + File.separator + Constants.WORK_DEFECT_IMG;
				String workVedio = workBase + File.separator + Constants.WORK_VEDIO;
				String workTaskBook =  workBase + File.separator + "工作任务书.docx";
				String workPiao =  workBase + File.separator + "工作票.docx";
				String standardWorkBook = workBase + File.separator + "标准化作业书.docx";
				FileUtil.mkdir(workDefectImg);
				FileUtil.mkdir(workVedio);
				FileUtil.copy(basePath + File.separator + "templates" + File.separator + "report" + File.separator + "word" + File.separator + "工作任务书模板.docx", workTaskBook);
				FileUtil.copy(basePath + File.separator + "templates" + File.separator + "report" + File.separator + "word" + File.separator + "工作票模板.docx", workPiao);
				FileUtil.copy(basePath + File.separator + "templates" + File.separator + "report" + File.separator + "word" + File.separator + "标准化作业书.docx", standardWorkBook);
				//ExportUtil.generate(workTaskBook, basePath + File.separator + "templates" + File.separator + "report" + File.separator + "word", "work_task.vm", null);
				//ExportUtil.generate(workPiao, basePath + File.separator + "templates" + File.separator + "report" + File.separator + "word", "work_ticket.vm", null);
				//ExportUtil.generate(standardWorkBook, basePath + File.separator + "templates" + File.separator + "report" + File.separator + "word", "standard_work.vm", null);
				/*
				
				//出库清单表
				String chukuQd = workBase + File.separator + "出库清单表.docx";
				doc = new XWPFDocument();
				p1 = doc.createParagraph();
				r1 = p1.createRun();
				r1.setBold(true);
				r1.setText("出库清单表");
				out = new FileOutputStream(chukuQd);
				doc.write(out);
				out.close();*/
			}
			else if(uiWork.getWorkType() == 3){
				
			}
			ar.setSuccess(true);
		} catch(Exception e){
			deviceRecipientService.delete(deviceRecipient);
			ar.setMsg("名称重复或者参数不正确");
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	public void add(Work work, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			workService.save(work);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/delete")
	public void delete(Ids ids, HttpServletRequest request, HttpServletResponse response, 
			HttpSession session){
		ActionResult ar = new ActionResult();
		
		try{
			for(long id : ids.getIds()){
				Work work = workService.findById(id);
				if(work != null){
					workDeviceService.deleteByWork(work.getId());
					workService.delete(work);
					String basePath = request.getServletContext().getRealPath("/");
					String workBase = basePath + File.separator + SysConfig.ATTACHEMENT + File.separator + SysConfig.WORK_DIR + File.separator + "飞巡作业" + File.separator + work.getName();
					FileUtil.delete(workBase);
				}
			}
			ar.setSuccess(true);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/delete/{id}")
	public void delete(@PathVariable long id, HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		try{
			Work work = (Work) workService.delete(id);
			String basePath = request.getServletContext().getRealPath("/");
			String workBase = basePath + File.separator + SysConfig.ATTACHEMENT + File.separator + SysConfig.WORK_DIR + File.separator + "飞巡作业" + File.separator + work.getName();
			FileUtil.delete(workBase);
			ar.setSuccess(true);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/detail/{id}")
	public ModelAndView detail(@PathVariable long id, HttpServletRequest request, HttpSession session, HttpServletResponse response, Map<String,Object> model){
		try {
			Work work = workService.findById(id);
			if(work.getDeviceRecipient() != null){
				work.getDeviceRecipient().getRecipientOrders().size();
				List<Device> devices = work.getDevices();
				if(devices != null && devices.size() != 0)
				{
					for(Device d : devices)
					{
						d.setDeviceRe(null);
						d.setWork(null);
					}
				}
				for(RecipientOrder order: work.getDeviceRecipient().getRecipientOrders()){
					order.setDeviceRecipient(null);
					order.setDevice(null);
				}				
			}
			model.put("work", JsonUtil.Object2Json(work));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Config.init(request, response, session, model);
		return new ModelAndView("workMgr/fx_work_detail", model);
	}
	
	@RequestMapping("/update")
	public void update(Work work, HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		try{
			workService.update(work);
			ar.setSuccess(true);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/lists")
	public void lists(@RequestParam String name, @RequestParam int type, HttpServletRequest request, HttpServletResponse response){
		String basePath = request.getServletContext().getRealPath("/");
		String rootPath = basePath + File.separator + SysConfig.ATTACHEMENT;
		String workPath = rootPath + File.separator + SysConfig.WORK_DIR; 
		String wts[] = {"充电作业", "飞巡作业", "调试作业"};
		String path = workPath + File.separator + wts[1] + File.separator + name;
		if(type == TYPE_DEFECT){
			path += File.separator + Constants.WORK_DEFECT_IMG;
		}
		else if(type == TYPE_VEDIO){
			path += File.separator + Constants.WORK_VEDIO;
		}
		ActionResult ar = new ActionResult();
		List<UIFile> uiFiles = FileUtil.list(basePath, path);
		if(uiFiles != null){
			ar.setSuccess(true);
			ar.setData(uiFiles);
		}
		else{
			ar.setMsg("列举文件失败");
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/download/{type}/{workname}/{filename}.{fex}")
	public void download(@PathVariable int type, @PathVariable String workname, @PathVariable String filename, @PathVariable String fex, HttpServletRequest request, HttpServletResponse response){
		String basePath = request.getServletContext().getRealPath("/");
		String rootPath = basePath + File.separator + SysConfig.ATTACHEMENT;
		String workPath = rootPath + File.separator + SysConfig.WORK_DIR; 
		String wts[] = {"充电作业", "飞巡作业", "调试作业"};
		filename = filename + "." + fex;
		String path = workPath + File.separator + wts[1] + File.separator + workname;
		if(type == TYPE_DEFECT){
			path += File.separator + Constants.WORK_DEFECT_IMG;
		}
		else if(type == TYPE_VEDIO){
			path += File.separator + Constants.WORK_VEDIO;
		}
		path += File.separator + filename;
		FileUtil.download(path,  filename, response);
	}
	
	@RequestMapping("/all")
	public void all(HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		String[] limit = request.getParameterValues("limit");
		String[] pages = request.getParameterValues("page");
		int pagesize = 25;
		int page = 1;
		if(limit.length > 0){
			pagesize = Integer.valueOf(limit[0]);
		}
		if(pages.length > 0){
			page = Integer.valueOf(pages[0]);
		}
		try{
			long total = workService.count();
			List<Work> works = workService.list(page, pagesize);
			for(Work work: works){
				work.setDeviceRecipient(null);
				User user = work.getWorker();
				user.setRoles(null);
			}
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setTotal(total);
			table.setRows(works);
			ar.setData(table);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/list_no_finish")
	public void listNotFinished(HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		try{
			List<Work> works = workService.listWorkNotStart();
			for(Work work: works){
				work.getDeviceRecipient().setRecipientOrders(null);
			}
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setRows(works);
			ar.setData(table);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/search")
	public void searchWork(UISearchWork uiSearchWork, HttpServletRequest request, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		String[] limit = request.getParameterValues("limit");
		String[] pages = request.getParameterValues("page");
		int pagesize = 25;
		int page = 1;
		if(limit.length > 0){
			pagesize = Integer.valueOf(limit[0]);
		}
		if(pages.length > 0){
			page = Integer.valueOf(pages[0]);
		}
		try{
			WorkType workType = workTypeService.findByType(uiSearchWork.getWorkType());
			long total = workService.countByCondition(workType, uiSearchWork.getTjType(), uiSearchWork.getStartTime(), 
									uiSearchWork.getEndTime(), uiSearchWork.getUserId());
			List<Work> works = workService.search(workType, uiSearchWork.getTjType(), uiSearchWork.getStartTime(), 
									uiSearchWork.getEndTime(), uiSearchWork.getUserId(), page, pagesize);
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setTotal(total);
			table.setRows(works);
			ar.setData(table);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/upload/{type}")
	public void upload(@PathVariable int type, @RequestParam(value = "file") MultipartFile file, @RequestParam long id, HttpServletRequest request, HttpSession session,
			HttpServletResponse response){
		ActionResult ar = new ActionResult();
		Work work = workService.findById(id);
		String filename = file.getOriginalFilename();
		String basePath = request.getServletContext().getRealPath("/") + File.separator + SysConfig.ATTACHEMENT + File.separator + SysConfig.WORK_DIR + File.separator + "飞巡作业"; 
		String path = basePath + File.separator + work.getName();
		if(type == TYPE_DEFECT){
			path += File.separator + Constants.WORK_DEFECT_IMG;
		}
		else if(type == TYPE_VEDIO){
			path += File.separator + Constants.WORK_VEDIO;
		}
		path += File.separator + filename;
		FileUtil.copyFile(file, path);
		ar.setSuccess(true);	
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/delfile")
	public void delete(@RequestParam int type, @RequestParam long id, @RequestParam String filename, HttpServletRequest request, HttpSession session,
			HttpServletResponse response){
		ActionResult ar = new ActionResult();
		Work work = workService.findById(id);
		String basePath = request.getServletContext().getRealPath("/") + File.separator + SysConfig.ATTACHEMENT + File.separator + SysConfig.WORK_DIR + File.separator + "飞巡作业"; 
		String path = basePath + File.separator + work.getName();
		if(type == TYPE_DEFECT){
			path += File.separator + Constants.WORK_DEFECT_IMG;
		}
		else if(type == TYPE_VEDIO){
			path += File.separator + Constants.WORK_VEDIO;
		}
		path += File.separator + filename;
		if(FileUtil.delete(path)){
			ar.setSuccess(true);
		}
		else{
			ar.setMsg("删除文件失败");
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/complete")
	public void complete(@RequestParam long id, HttpServletRequest request, HttpSession session,
			HttpServletResponse response){
		ActionResult ar = new ActionResult();
		Work work = workService.findById(id);
		if(work == null){
			ar.setMsg("没有该作业");
		}
		else{
			if(work.getOutCount() == 0) //所有设备已入库后才能完成该任务
			{
				work.setEndTime(new Date());
				work.setState(2);
				try{
					workService.update(work);
					ar.setSuccess(true);
				}
				catch(Exception e){
					ar.setMsg(e.getMessage());
				}
			}
			else
			{
				ar.setSuccess(false);
				ar.setMsg("所有设备须入库后才能完成该任务");
			}
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/start")
	public void start(@RequestParam long id, HttpServletRequest request, HttpSession session,
			HttpServletResponse response){
		ActionResult ar = new ActionResult();
		Work work = workService.findById(id);
		if(work == null){
			ar.setMsg("没有该作业");
		}
		else{
			work.setState(1);  //开始任务
			try{
				workService.update(work);
				ar.setSuccess(true);
			}
			catch(Exception e){
				ar.setMsg(e.getMessage());
			}
		}
		ResponseUtil.returnJson(response, ar);
	}
}
